import React, { Component } from "react";
import { Card, Button, Table, Modal, message } from "antd";
import { reqRoles, reqAddRole, reqUpdateRole } from "../../api";
import { formdateDate } from "../../util/datatutil";
import Addform from "./addform";
import Authform from "./authform";
import storeutils from "../../util/storeutil";
class Role extends Component {
  state = {
    roles: [], // 角色列表
    role: {},
    isShowAdd: false, // 添加弹框
    isShowAuth: false, // 授权弹出框
  };
  constructor(props) {
    super(props);
    this.auth = React.createRef();
  }
  initColumn = () => {
    this.columns = [
      {
        title: "角色名称",
        dataIndex: "name",
      },
      {
        title: "创建时间",
        dataIndex: "create_time",
        render: (create_time) => formdateDate(create_time),
      },
      {
        title: "授权时间",
        dataIndex: "auth_time",
        render: formdateDate,
      },
      {
        title: "授权人",
        dataIndex: "auth_name",
      },
    ];
  };
  getRoles = async () => {
    const result = await reqRoles();
    if (result.status === 0) {
      const roles = result.data;
      this.setState({
        roles,
      });
    }
  };
  onRow = (role) => {
    return {
      onClick: (event) => {
        console.log(222, role);
        this.setState({
          role,
        });
      },
    };
  };
  // 添加角色
  addRole = () => {
    this.form.validateFields(async (err, values) => {
      if (!err) {
        this.setState({
          isShowAdd: false,
        });
        const { roleName } = values;
        this.form.resetFields();
        const result = await reqAddRole(roleName);
        if (result.status === 0) {
          message.success("添加角色成功");
          const role = result.data;
          this.setState((state) => ({
            roles: [...state.roles, role],
          }));
        } else {
          message.success("添加角色失败");
        }
      }
    });
  };
  // 修改角色权限
  updateRole = async () => {
    this.setState({
      isShowAuth: false,
    });
    const role = this.state.role;
    const menus = this.auth.current.getMenus(); //父组件调用子组件获取最新的选中的值
    role.menus = menus;
    role.auth_time = Date.now();
    role.auth_name = storeutils.getUser().username; //获取授权人
    const result = await reqUpdateRole(role);
    if (result.status === 0) {
      if (role._id == storeutils.getUser().role_id) {
        storeutils.removeUser();
        this.props.history.replace("/login");
        message.success("修改当前成功");
      } else {
        message.success("设置角色成功");
        this.setState({
          roles: [...this.state.roles],
        });
      }
    }
  };
  componentWillMount() {
    this.initColumn();
  }
  componentDidMount() {
    this.getRoles();
  }
  render() {
    const { roles, role, isShowAdd, isShowAuth } = this.state;
    const title = (
      <span>
        <Button
          type="primary"
          onClick={() => this.setState({ isShowAdd: true })}
        >
          创建角色
        </Button>
        <Button
          type="primary"
          onClick={() => this.setState({ isShowAuth: true })}
          disabled={!role._id}
        >
          设置角色权限
        </Button>
      </span>
    );
    return (
      <Card title={title}>
        <Table
          bordered
          rowKey="_id"
          columns={this.columns}
          dataSource={roles}
          rowSelection={{
            type: "radio",
            selectedRowKeys: [role._id],
            onSelect: (role) => {
              console.log(role);
              this.setState({
                role,
              });
            },
          }}
          onRow={this.onRow}
        />
        <Modal
          title="添加角色"
          visible={isShowAdd}
          onOk={this.addRole}
          onCancel={() => {
            this.setState({
              isShowAdd: false,
            });
          }}
        >
          <Addform
            setForm={(form) => {
              this.form = form;
            }}
          />
        </Modal>
        <Modal
          title="设置角色"
          visible={isShowAuth}
          onCancel={() => {
            this.setState({ isShowAuth: false });
          }}
          onOk={this.updateRole}
        >
          <Authform role={role} ref={this.auth} />
        </Modal>
      </Card>
    );
  }
}

export default Role;
